package com.example.k8s.hello.common.utils;

import com.example.k8s.hello.common.exception.ApiExEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Path;

public class HttpContextUtils {

	public static ServletRequestAttributes getRequestAttributes() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return (ServletRequestAttributes) attributes;
	}

	/**
	 * 获取request
	 */
	public static HttpServletRequest getRequest() {
		return getRequestAttributes().getRequest();
	}

	/**
	 * 获取response
	 */
	public static HttpServletResponse getResponse() {
		return getRequestAttributes().getResponse();
	}



	public static String getDomain(){
		HttpServletRequest request = getRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getRequest();
		return request.getHeader("Origin");
	}

	public static void download(Path path) throws IOException {
		ApiExEnum.A0010.assertTrue(path.toFile().exists(), "文件不存在");

		try (FileInputStream in = new FileInputStream(path.toFile())) {
			download(in, path.getFileName().toString());
		}
	}
	public static void download(InputStream in, String fileName) throws IOException {
		HttpServletResponse response = getResponse();
		response.reset();

		String name = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
		response.addHeader("Content-Disposition", "attachment;filename=" + name);

		response.setCharacterEncoding("utf-8");
		response.setContentType("application/octet-stream");
		response.setContentLength(in.available());

		IOUtils.copyLarge(in, response.getOutputStream());
	}

}
